package pvt_chat

import (
	"context"
	"errors"
	"github.com/olivere/elastic/v7"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/json"
	global2 "longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/utils"
	sort2 "sort"
)

const (
	AnonymousSender = iota // 匿名用户
	CustomSender           // 后台客服消息
	UserSender             // 用户消息
)

type HistoryById struct {
	Id string `json:"id"`
	History
}

type History struct {
	SessionId  string `json:"session_id"`  // 会话ID
	SenderUid  string `json:"sender_uid"`  // 用户ID
	SenderTag  int    `json:"sender_tag"`  // 发送用户是否位匿名用户 0 匿名 1 客服 2 用户
	ReceiveUid string `json:"receive_uid"` // 主播ID
	Content    string `json:"content"`     // 聊天内容
	SendTime   int64  `json:"send_time"`   // 发言时间
	ImgUrl     string `json:"img_url"`     // 图片地址
}

const PrivateChatHistoryIndexName = "private_history"

func (h History) WriteToEs() (string, bool) {
	resp, err := global2.GetEs().Index().Index(PrivateChatHistoryIndexName).BodyJson(h).Do(context.Background())
	if err != nil {
		global2.Log.Errorf("err:%v", err)
		return "", false
	}
	return resp.Id, true
}

func BatchWriteToEs(records []*elastic.BulkIndexRequest) error {
	if len(records) < 1 {
		return errors.New("len lt 1")
	}
	bulk := global2.GetEs().Bulk()
	for i := range records {
		bulk.Add(records[i])
	}
	res, err := bulk.Do(context.Background())
	if err != nil {
		global2.Log.Errorf("exec bulk to es : %v", err)
		return err
	}
	for _, item := range res.Failed() {
		global2.Log.Errorf("write to es err: %s", item.Error.Reason)
	}
	return nil
}

func GetHistory(sessionIds []string, page, limit int) ([]HistoryById, int64) {
	start := (page - 1) * limit
	// 聊天排序，查询时按倒序分页, 查出来后再reverse,得出的数据就是按时间正序，最后一条就是最新的
	sort := elastic.NewFieldSort("send_time").Desc()
	query := elastic.NewBoolQuery().Filter(elastic.NewTermsQuery("session_id", utils.EsTermsTransSlice(sessionIds)...))
	res, err := global2.GetEs().Search(PrivateChatHistoryIndexName).
		From(start).
		Size(limit).
		PostFilter(query).
		SortBy(sort).
		Do(context.Background())
	if err != nil {
		global2.Log.Errorf("search error: %v", err)
		return nil, 0
	}
	var item HistoryById
	records := make([]HistoryById, 0)
	for _, hit := range res.Hits.Hits {
		if err := json.Unmarshal(hit.Source, &item); err != nil {
			global2.Log.Errorf("unmarshal error: %v", err)
			continue
		}
		item.Id = hit.Id
		records = append(records, item)
	}
	//reverse
	//for i, j := 0, len(records)-1; i < j; i, j = i+1, j-1 {
	//	records[i], records[j] = records[j], records[i]
	//}
	sort2.Slice(records, func(i, j int) bool {
		if records[i].SendTime < records[j].SendTime {
			return true
		}
		return false
	})
	return records, res.TotalHits()
}

func DelHistory(sessionIds []int) error {
	query := elastic.NewBoolQuery().Filter(elastic.NewTermsQuery("session_id", utils.EsTermsTransSlice(sessionIds)...))
	_, err := global2.GetEs().DeleteByQuery(PrivateChatHistoryIndexName).Query(query).Do(context.Background())
	if err != nil {
		global2.Log.Errorf("delete error: %v", err)
		return err
	}
	return nil
}
